﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int count = 0;//用于定时器计数
        int time = 15;//存储设定的定时值
        int flag = 0;
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);//系统dll导入ini写函数
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);//系统dll导入ini读函数
        string FileName = System.AppDomain.CurrentDomain.BaseDirectory + "data.ini";//ini文件名
        StringBuilder temp = new StringBuilder(255);//存储读出ini内容变量

        string CurrentPortName;
        public Form1()
        {
            InitializeComponent();
            /*****************非常重要************************/
            //手动添加的事件
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);//必须手动添加事件处理程序
            serialPort1.Encoding = Encoding.GetEncoding("GB2312");                                  //串口接收编码
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; //
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(Form1_FormClosing);

        }
        public static string gb2312_utf8(string text)
        {
            //声明字符集   
            System.Text.Encoding utf8, gb2312;
            //gb2312   
            gb2312 = System.Text.Encoding.GetEncoding("gb2312");
            //utf8   
            utf8 = System.Text.Encoding.GetEncoding("utf-8");
            byte[] gb;
            gb = gb2312.GetBytes(text);
            gb = System.Text.Encoding.Convert(gb2312, utf8, gb);
            //返回转换后的字符   
            return utf8.GetString(gb);
        }
        private void Form1_Load(object sender, EventArgs e)
        {

            ovalShape1.FillColor = Color.Gray;
            SearchAndAddSerialToComboBox(serialPort1, comboBox1);
            
            GetPrivateProfileString("PortData", "PortName", "COM1", temp, 256, FileName);//读取ini值，默认是COM1
            comboBox1.Text = temp.ToString();//初始化

        }
        private void Form1_FormClosing(object sender, EventArgs e)
        {
            WritePrivateProfileString("PortData", "PortName", CurrentPortName, FileName);//窗口关闭，保存
            
        }
        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();//开始计时
            if (serialPort1.IsOpen)                                     //串口打开就关闭
            {
                //timer1.Start();//开始计时
                try
                {
                    serialPort1.Close();
                }
                catch { }                                               //确保万无一失
                ovalShape1.FillColor = Color.Gray;
                button1.Text = "打开串口";
                button1.BackColor = Color.Gray;
            }
            else
            {
                try
                {
                    serialPort1.PortName = comboBox1.Text;              //端口号
                    //serialPort1.BaudRate = Convert.ToInt32(comboBox1.Text, 10);//十进制数据转换
                    serialPort1.Open();                                 //打开端口
                    CurrentPortName = comboBox1.Text;
                    ovalShape1.FillColor = Color.Green;
                    button1.Text = "关闭串口";
                    button1.BackColor = Color.Red;
                }
                catch
                {
                    MessageBox.Show("串口打开失败", "错误");
                }
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            count++;//记当前秒
            if (count == time)
            {
                timer1.Stop();//时间到，停止计时
                count = 0;
                flag = 1;
                timer1.Start();//开始计时
            }
        }
        /*******************串口数据接收事件********************/
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            
            //Console.WriteLine(count);
            if (flag == 0)
            {
                if (!radioButton3.Checked)//如果接收模式为文本字符模式
                {
                    textBox1.AppendText(serialPort1.ReadExisting());                                //串口类会自动处理汉字，所以不需要特别转换
                }
                else
                {
                    //如果接收模式为十六数值接收
                    byte[] data = new byte[serialPort1.BytesToRead];                                //定义缓冲区，因为串口事件触发时有可能收到不止一个字节
                    serialPort1.Read(data, 0, data.Length);                                         //此处需要强制类型转换，将(int)类型数据转换为(byte类型数据，8位的数据
                    foreach (byte Member in data)                                                   //遍历用法
                    {
                        string str = Convert.ToString(Member, 16).ToUpper();                        //转换为大写十六进制字符串
                        textBox1.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");      //空位补“0”
                    }
                }
            }
            else if (flag == 1)
            {
                flag = 0;
                string constr = "server=172.22.161.67;User Id=wlw;password=axiao7;Database=wlw;";//连接小栖的服务器
                //TRUNCATE TABLE data;
                //string constr = "server=localhost;User Id=root;password=1234;Database=wlw"; //连接本地的mysql服务器
                MySqlConnection mycon = new MySqlConnection(constr);
                mycon.Open();
                if (!radioButton3.Checked)//如果接收模式为文本字符模式
                {
                    string str = serialPort1.ReadExisting();//字符串方式读
                    str = gb2312_utf8(str);
                    string str_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    MySqlCommand mycmd = new MySqlCommand("insert into data (info,time) values('" + str + "','" + str_time + "' )", mycon);

                    if (mycmd.ExecuteNonQuery() > 0)
                    {
                        textBox1.AppendText(str);
                    }
                    mycon.Close();
                }
                else
                {
                    //如果接收模式为十六数值接收
                    byte[] data = new byte[serialPort1.BytesToRead];                                //定义缓冲区，因为串口事件触发时有可能收到不止一个字节
                    serialPort1.Read(data, 0, data.Length);                                         //此处需要强制类型转换，将(int)类型数据转换为(byte类型数据，8位的数据
                    foreach (byte Member in data)                                                   //遍历用法
                    {
                        string str = Convert.ToString(Member, 16).ToUpper();                        //转换为大写十六进制字符串
                        textBox1.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");      //空位补“0”
                    }
                }
                
            }

        }
        private void button3_Click(object sender, EventArgs e)
        {
            byte[] Data = new byte[1];//作用同上集
            if (serialPort1.IsOpen)//判断串口是否打开，如果打开执行下一步操作
            {
                if (textBox2.Text != "")
                {
                    if (!radioButton1.Checked)//如果发送模式是字符模式
                    {
                        try
                        {
                            serialPort1.WriteLine(textBox2.Text);//写数据
                        }
                        catch
                        {
                            MessageBox.Show("串口数据写入错误", "错误");//出错提示
                            serialPort1.Close();
                            button1.Enabled = true;//打开串口按钮可用
                            //button2.Enabled = false;//关闭串口按钮不可用
                        }
                    }
                    else
                    {
                        //如果此时用户输入字符串中含有非法字符（字母，汉字，符号等等，try，catch块可以捕捉并提示）
                        try
                        {
                            for (int i = 0; i < (textBox2.Text.Length - textBox2.Text.Length % 2) / 2; i++)//转换偶数个
                            {
                                Data[0] = Convert.ToByte(textBox2.Text.Substring(i * 2, 2), 16);           //转换
                                serialPort1.Write(Data, 0, 1);
                            }
                            if (textBox2.Text.Length % 2 != 0)
                            {
                                Data[0] = Convert.ToByte(textBox2.Text.Substring(textBox2.Text.Length - 1, 1), 16);//单独处理最后一个字符
                                serialPort1.Write(Data, 0, 1);                              //写入
                            }
                        }
                        catch
                        {
                            MessageBox.Show("数据转换错误，请输入数字。", "错误");
                        }
                    }
                }
            }
        }
        private void SearchAndAddSerialToComboBox(SerialPort MyPort, ComboBox MyBox)
        {                                                               //将可用端口号添加到ComboBox
            //string[] MyString = new string[20];                       //最多容纳20个，太多会影响调试效率
            string Buffer;                                              //缓存
            MyBox.Items.Clear();                                        //清空ComboBox内容
            //int count = 0;
            for (int i = 1; i < 45; i++)                                //循环
            {
                try                                                     //核心原理是依靠try和catch完成遍历
                {
                    Buffer = "COM" + i.ToString();
                    MyPort.PortName = Buffer;
                    MyPort.Open();                                      //如果失败，后面的代码不会执行
                    //MyString[count] = Buffer;
                    MyBox.Items.Add(Buffer);                            //打开成功，添加至下俩列表
                    MyPort.Close();                                     //关闭
                    //count++;
                }
                catch
                {
                    //count--;
                }
            }
            //MyBox.Text = MyString[0];                                   //初始化
        }
        private void button2_Click(object sender, EventArgs e)
        {
            SearchAndAddSerialToComboBox(serialPort1, comboBox1);
        }
        private void button4_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";//清空接收区
        }
        private void button5_Click(object sender, EventArgs e)
        {
            textBox2.Text = "";//接空发送区

        }
        private void button6_Click(object sender, EventArgs e)
        {
            //ovalShape1.FillColor = Color.Green;

            button6.BackColor = Color.Red;
            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("要写入的文件内容不能为空");
            }
            else
            {
                //设置保存文件的格式
                saveFileDialog1.Filter = "文本文件(*.txt)|*.txt";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    //使用“另存为”对话框中输入的文件名实例化StreamWriter对象
                    StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, true);
                    //向创建的文件中写入内容
                    sw.WriteLine(textBox1.Text);
                    //关闭当前文件写入流
                    sw.Close();
                    button6.BackColor = Color.Gray;
                    //textBox1.Text = string.Empty;
                }
            }
        }
        private void label1_Click(object sender, EventArgs e)
        {

        }
        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {

        }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void ovalShape1_Click(object sender, EventArgs e)
        {

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void groupBox4_Enter(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }
    }
}